package com.example.shinelonx6.myapplication;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity {
    private TabHost tabHost;
    private MediaPlayer mediaPlayer;
    private List<String>audioList = new ArrayList<String>();
    private int currentltem = 0;
    private Button pause;
    private static String[] imageFormatSet = new String[]{"mp3","wav","3gp"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //选项卡
        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();
        LayoutInflater inflater =LayoutInflater.from(this);
        inflater.inflate(R.layout.tab1,tabHost.getTabContentView());
        inflater.inflate(R.layout.tab2,tabHost.getTabContentView());
        inflater.inflate(R.layout.tab3,tabHost.getTabContentView());
        tabHost.addTab(tabHost.newTabSpec("tab01")
            .setIndicator("列表")
            .setContent(R.id.LinearLayout01));
        tabHost.addTab(tabHost.newTabSpec("tab02")
            .setIndicator("歌曲")
            .setContent(R.id.LinearLayout02));
        tabHost.addTab(tabHost.newTabSpec("tab03")
            .setIndicator("个人信息")
            .setContent(R.id.LinearLayout03));

        //tab1
        mediaPlayer = new MediaPlayer();
        Button play = (Button) findViewById(R.id.play);
        Button stop = (Button) findViewById(R.id.stop);
        pause = (Button) findViewById(R.id.pause);
        Button pre = (Button) findViewById(R.id.pre);
        Button next = (Button) findViewById(R.id.next);
        audioList();

        //为 media player添加监听器
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                nextMusic();
            }
        });
        //为上一首按钮添加监听器
        pre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                preMusic();
            }
        });
        //为播放按钮添加监听器
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playMusic(audioList.get(currentltem));
            }
        });
        //为暂停按钮添加监听器
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                    ((Button)v).setText("继续");
                }else{
                    mediaPlayer.start();
                    ((Button)v).setText("暂停");
                }
            }
        });
        //为停止按钮添加监听器
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.stop();
                }
                pause.setEnabled(false);
            }
        });
        //给下一首按钮添加监听器
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextMusic();
            }
        });
    }
    //获取SD卡文件，创建一个适配器，与listview关联，并显示
    private void audioList() {
        Log.i("log","This is Information");
        getFiles(Environment.getExternalStorageDirectory().getAbsolutePath()+"/myMusic");
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,audioList);
        final ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
        //单击列表时
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
                currentltem = position;
                playMusic(audioList.get(currentltem));
            }

        });
    }
    //播放音乐
    public void playMusic(String path) {
        try{
            if(mediaPlayer.isPlaying()){
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.start();
            pause.setText("暂停");
            pause.setEnabled(true);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //判断是否为音乐文件
    private static boolean isAudioFile(String path){
        for(String format:imageFormatSet){
            if(path.contains(format)){
                return true;
            }
        }
        return false;
    }
    //通过递归，获取SD卡，所有音频文件
    private void getFiles(String url) {
        Log.i("lcj ",url);
        File files = new File(url);
        File[] file = files.listFiles();
        try{
            for(File f:file){
                if(f.isDirectory()){
                    getFiles(f.getAbsolutePath());
                }else{
                    if(isAudioFile(f.getPath())){
                        audioList.add(f.getPath());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //下一首
    void nextMusic(){
        if(++currentltem>=audioList.size()){
            currentltem = 0;
        }
        playMusic(audioList.get(currentltem));
    }
    //上一首
    void  preMusic(){
        if(--currentltem >=0){
            if(currentltem>=audioList.size()){
                currentltem = 0;
            }
        }else {
            currentltem = audioList.size()-1;
        }
        playMusic(audioList.get(currentltem));
    }
    //退出时，停止音乐
    protected void onDestroy(){
        if (mediaPlayer.isPlaying()){
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        super.onDestroy();
    }


   
    



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
